<template>
  <view class="container">
    <tui-list-view>
      <tui-list-cell v-for="(item, index) in catalogs" :key="index" :index="index" @click="read">
        <text
          class="story-chapter-name"
          :class="{ active: item.url == url || item.name == chapterTitle }"
        >{{ item.name }}</text>
      </tui-list-cell>
    </tui-list-view>
    <tui-operation :buttons="operation" @button-click="tapOperation" />

    <tui-modal
      color="#333"
      :show="changeConfirm"
      :content="'确定更换到此源吗？'"
      :size="32"
      :button="confirmButtons"
      @click="handleChange"
      @cancel="hideConfirm"
    ></tui-modal>
    <tui-scroll-top :scrollTop="scrollTop"></tui-scroll-top>
    <tui-page-loading type="dots" :show="loading" />
  </view>
</template>

<script>
import tuiOperation from "@/components/operation/operation.vue";
import tuiListView from "@/components/list-view/list-view.vue";
import tuiListCell from "@/components/list-cell/list-cell.vue";
import tuiModal from "@/components/modal/modal";
import tuiPageLoading from "@/components/page-loading/page-loading.vue";
import tuiScrollTop from "@/components/scroll-top/scroll-top";
import navigateTo from "@/pages/read/navigateTo.js";
import { mapState, mapMutations } from "vuex";

export default {
  components: {
    tuiOperation,
    tuiListView,
    tuiListCell,
    tuiPageLoading,
    tuiScrollTop,
    tuiModal
  },
  data() {
    return {
      catalogs: [],
      asc: true,
      url: "",
      chapterTitle: "",
      loading: false,
      scrollTop: 0,
      changeConfirm: false,
      changeIndex: 0,
      confirmButtons: [
        {
          text: "取消",
          type: "gray"
        },
        {
          text: "确定"
        }
      ]
    };
  },
  computed: {
    ...mapState(["bookshelfs"]),
    operation() {
      return [
        {
          type: "white",
          shape: "rightAngle",
          size: "small",
          text: "刷新",
          tap: ""
        },
        {
          type: "white",
          shape: "rightAngle",
          size: "small",
          text: this.asc ? "逆序" : "正序"
        }
      ];
    }
  },
  onLoad(options) {
    if (!options.source_id || !options.read_url) {
      this.tui.toast("参数缺失");
      setTimeout(() => {
        uni.navigateBack({
          delta: 1
        });
      }, 1000);
    } else {
      for (let key in options) {
        this[key] = decodeURIComponent(options[key]);
      }
      this.init();
      if (this.source_name) {
        uni.setNavigationBarTitle({
          title: "更换源"
        });
      }
    }
  },
  onPageScroll(e) {
    this.scrollTop = e.scrollTop;
  },
  methods: {
    ...mapMutations(["setBookshelfs"]),
    init(callback) {
      this.loading = true;
      this.callFunc({
        name: "queryCatalogs",
        data: {
          source_id: this.source_id,
          read_url: this.read_url
        }
      })
        .then(res => {
          if (res.result.errMsg == "ok") {
            const data = this.asc
              ? res.result.data.catalogs
              : res.result.data.catalogs.reverse();
            this.catalogs = data;
            this.name = res.result.data.name;
            // 滚动到所在章节目录
            this.$nextTick(this.scrollPosition);
            // setTimeout(this.scrollPosition, 0);
          } else {
            this.tui.toast(res.result.errMsg);
          }
          this.loading = false;
          callback && callback();
        })
        .catch(err => {
          this.loading = false;
          this.tui.toast("请求目录失败");
          setTimeout(() => {
            uni.navigateBack({
              delta: 1
            });
          }, 1000);
        });
    },
    // 滚动到所在章节目录
    scrollPosition() {
      if (!this.url && !this.chapterTitle) {
        return;
      }
      const query = uni.createSelectorQuery().in(this);
      query
        .select(".story-chapter-name.active")
        .boundingClientRect(data => {
          if (data) {
            uni.pageScrollTo({
              scrollTop: data.top - 30,
              duration: 120
            });
          }
          // 章节名不一致
        })
        .exec();
    },
    tapOperation(index) {
      if (index == 0) {
        this.init(this.id, this.url);
      } else if (index == 1) {
        this.catalogs.reverse();
        this.asc = !this.asc;
      }
    },
    read({ index }) {
      // console.log(index);
      if (this.source_name) {
        // 更换源
        this.changeConfirm = true;
        this.changeIndex = index;
      } else {
        // 阅读
        const { url } = this.catalogs[index];
        const { source_id, read_url, _id, name } = this;
        navigateTo("pages/read/read", { source_id, read_url, url, _id, name });
      }
    },
    handleChange({ index }) {
      if (index == 0) {
        this.hideConfirm();
        return;
      }
      console.log(this.bookshelfs);
      const book = this.bookshelfs.find(bs => bs._id == this._id);
      console.log(this._id, book);
      if (!book) {
        this.tui.toast("该书籍不在书架中");
        this.hideConfirm();
        return;
      }
      this.loading = true;
      const other_sources = [];
      book.other_sources.forEach(os => {
        if (os.source_id != this.source_id) {
          other_sources.push(os);
        }
      });
      other_sources.push({
        source_id: book.source_id,
        read_url: book.read_url,
        source_name: book.source_name
      });
      const data = {
        author: this.author,
        cover: this.cover,
        hasNew: true,
        latest_chapter_url: this.latest_chapter_url,
        name: this.name,
        other_sources: other_sources,
        read_url: this.read_url,
        source_id: this.source_id,
        source_name: this.source_name,
        url: this.catalogs[this.changeIndex].url,
        page: 0
      };
      this.db
        .collection("bookshelfs")
        .doc(this._id)
        .update({
          data: data
        })
        .then(res => {
          // console.log(res);
          if (res.stats && res.stats.updated) {
            const bookshelfs = [];
            this.bookshelfs.forEach(bs => {
              if (bs._id == this._id) {
                bookshelfs.push({ ...bs, ...data });
              } else {
                bookshelfs.push(bs);
              }
            });
            this.setBookshelfs(bookshelfs);
            this.$nextTick(() => {
              navigateTo("pages/read/read", {
                _id: this._id
              });
            });
          } else {
            this.tui.toast(res.errMsg);
          }
          this.hideConfirm();
          this.loading = false;
        });
    },
    hideConfirm() {
      this.changeConfirm = false;
    }
  }
};
</script>

<style>
.container {
  padding-bottom: 110rpx;
}
.story-chapter-name {
  font-size: 28rpx;
  color: #aaa;
  line-height: 30rpx;
}
.story-chapter-name.active {
  color: #6cc;
}
</style>
